<template>
  <div class="user-info-root">
    <div class="user-info-container">
      <div class="user-info-card">
        <div class="card-header">
          <h2 class="title">个人信息</h2>
          <el-button
            type="primary"
            link
            class="edit-avatar"
            @click="handleEditAvatar"
            >编辑头像</el-button
          >
        </div>

        <div class="card-content">
          <div class="info-section">
            <div class="info-row">
              <span class="info-label">用户名:</span>
              <span class="info-value">{{
                userStore.userInfo?.username || 'admin'
              }}</span>
            </div>

            <div class="info-row">
              <span class="info-label">姓名:</span>
              <span class="info-value">{{
                userStore.userInfo?.name || '管理员'
              }}</span>
            </div>

            <div class="info-row">
              <span class="info-label">电话:</span>
              <span class="info-value">{{
                userStore.userInfo?.phone || '暂无信息'
              }}</span>
            </div>

            <div class="info-row">
              <span class="info-label">身份证:</span>
              <span class="info-value">{{
                userStore.userInfo?.idNu || '暂无信息'
              }}</span>
            </div>

            <div class="info-row">
              <span class="info-label"></span>
              <span class="info-value">
                <el-button type="primary" @click="showPasswordDrawer = true"
                  >修改密码</el-button
                >
              </span>
            </div>
          </div>

          <div class="avatar-section">
            <el-avatar
              :size="120"
              :src="userStore.userInfo?.avatar || defaultAvatar"
              class="user-avatar"
            />
          </div>
        </div>
      </div>
    </div>

    <!-- 修改密码抽屉 -->
    <el-drawer
      v-model="showPasswordDrawer"
      title="修改密码"
      :size="400"
      :destroy-on-close="true"
      direction="rtl"
    >
      <el-form
        ref="passwordFormRef"
        :model="passwordForm"
        :rules="passwordRules"
        label-width="120px"
        label-position="left"
      >
        <el-form-item label="原密码" prop="originPassword">
          <el-input
            v-model="passwordForm.originPassword"
            type="password"
            placeholder="请输入原密码"
            show-password
          />
        </el-form-item>

        <el-form-item label="新密码" prop="newPassword">
          <el-input
            v-model="passwordForm.newPassword"
            type="password"
            placeholder="请输入新密码"
            show-password
          />
        </el-form-item>

        <el-form-item label="确认新密码" prop="checkedPassword">
          <el-input
            v-model="passwordForm.checkedPassword"
            type="password"
            placeholder="请再次输入新密码"
            show-password
          />
        </el-form-item>

        <el-form-item>
          <el-button
            type="primary"
            @click="submitPasswordChange"
            :loading="passwordLoading"
          >
            确认修改
          </el-button>
          <el-button @click="showPasswordDrawer = false">取消</el-button>
        </el-form-item>
      </el-form>
    </el-drawer>

    <!-- 头像上传对话框 -->
    <el-dialog
      v-model="showAvatarDialog"
      title="上传头像"
      width="400px"
      :before-close="handleCloseAvatarDialog"
    >
      <div class="avatar-upload-container">
        <!-- 预览区域 - 修改为可点击和可拖拽 -->
        <div
          class="avatar-preview"
          @click="triggerFileSelect"
          @dragover.prevent="handleDragOver"
          @dragleave.prevent="handleDragLeave"
          @drop.prevent="handleDrop"
          :class="{ 'drag-over': isDragging }"
        >
          <img
            v-if="avatarUrl"
            :src="avatarUrl"
            alt="头像预览"
            class="preview-image"
          />
          <div v-else class="preview-placeholder">
            <el-icon><Plus /></el-icon>
            <span>点击或拖拽图片到此处上传</span>
          </div>
        </div>

        <!-- 操作按钮 -->
        <div class="avatar-actions">
          <input
            type="file"
            ref="fileInput"
            style="display: none"
            accept="image/jpeg,image/png,image/gif"
            @change="handleFileChange"
          />
          <el-button type="primary" @click="triggerFileSelect"
            >选择图片</el-button
          >
          <el-button
            type="success"
            :disabled="!avatarUrl"
            :loading="avatarLoading"
            @click="upLoadAvatar"
          >
            上传头像
          </el-button>
        </div>

        <!-- 提示信息 -->
        <div class="avatar-tips">
          <p>支持 JPG、PNG、GIF 格式，文件大小不超过 2MB</p>
        </div>
      </div>
    </el-dialog>
  </div>
</template>

<script setup>
import { useUserStore } from '@/store/modules/user'
import { ref, computed, reactive } from 'vue'
import { ElMessage } from 'element-plus'
import { Plus } from '@element-plus/icons-vue'
import { Encrypt } from '@/utils/secret'
import { uploadAvatar, updatePassword } from '@/api/user'

const userStore = useUserStore()

// 默认头像
const defaultAvatar =
  userStore.userInfo?.avatar ||
  'https://api.dicebear.com/7.x/avataaars/svg?seed=student'

// 头像上传相关
const showAvatarDialog = ref(false)
const avatarLoading = ref(false)
const avatarUrl = ref('')
const fileInput = ref(null)
const isDragging = ref(false)

// 编辑头像功能
const handleEditAvatar = () => {
  showAvatarDialog.value = true
  avatarUrl.value = ''
}

// 处理拖拽相关事件
const handleDragOver = (e) => {
  isDragging.value = true
}

const handleDragLeave = (e) => {
  isDragging.value = false
}

const handleDrop = (e) => {
  isDragging.value = false
  const files = e.dataTransfer.files
  if (files.length > 0) {
    // 只取第一个文件
    processFile(files[0])
  }
}

// 处理文件上传和验证
const processFile = (file) => {
  if (!file) return

  // 验证文件类型
  const isImage = file.type.startsWith('image/')
  if (!isImage) {
    ElMessage.error('请上传图片文件')
    return
  }

  // 验证文件大小（最大2MB）
  const isLt2M = file.size / 1024 / 1024 < 2
  if (!isLt2M) {
    ElMessage.error('图片大小不能超过2MB')
    return
  }

  // 创建预览
  avatarUrl.value = URL.createObjectURL(file)

  // 手动设置文件到input元素，方便后续上传
  const dataTransfer = new DataTransfer()
  dataTransfer.items.add(file)
  fileInput.value.files = dataTransfer.files
}

// 选择文件
const handleFileChange = (e) => {
  const file = e.target.files[0]
  processFile(file)
}

// 点击上传按钮触发文件选择
const triggerFileSelect = () => {
  fileInput.value.click()
}

// 上传头像
const upLoadAvatar = async () => {
  if (!avatarUrl.value) {
    ElMessage.warning('请先选择图片')
    return
  }

  const fileObj = fileInput.value.files[0]
  if (!fileObj) return

  avatarLoading.value = true

  try {
    const formData = new FormData()
    formData.append('file', fileObj)

    // 调用头像上传API
    const res = await uploadAvatar(formData)

    if (res.code == 1) {
      ElMessage.success('头像上传成功')
    } else {
      ElMessage.error('头像上传失败')
      return
    }

    // 更新用户信息（包含新头像）
    await userStore.getUserinfo()
    showAvatarDialog.value = false
  } catch (error) {
    console.log(error)
    ElMessage.error('头像上传失败')
  } finally {
    avatarLoading.value = false
    // 释放预览URL
    if (avatarUrl.value) {
      URL.revokeObjectURL(avatarUrl.value)
    }
  }
}

// 修改密码相关
const showPasswordDrawer = ref(false)
const passwordLoading = ref(false)
const passwordFormRef = ref(null)

const passwordForm = reactive({
  originPassword: '',
  newPassword: '',
  checkedPassword: '',
})

const validatecheckedPassword = (rule, value, callback) => {
  if (value !== passwordForm.newPassword) {
    callback(new Error('两次输入的密码不一致'))
  } else {
    callback()
  }
}

const passwordRules = {
  originPassword: [
    { required: true, message: '请输入原密码', trigger: 'blur' },
  ],
  newPassword: [
    { required: true, message: '请输入新密码', trigger: 'blur' },
    { min: 6, message: '密码长度不能少于6个字符', trigger: 'blur' },
  ],
  checkedPassword: [
    { required: true, message: '请再次输入新密码', trigger: 'blur' },
    { validator: validatecheckedPassword, trigger: 'blur' },
  ],
}

// 修改密码
const submitPasswordChange = async () => {
  if (!passwordFormRef.value) return

  await passwordFormRef.value.validate(async (valid, fields) => {
    if (valid) {
      passwordLoading.value = true
      try {
        // 密码加密
        const params = {
          originPassword: passwordForm.originPassword,
          newPassword: Encrypt(passwordForm.newPassword),
          checkedPassword: Encrypt(passwordForm.checkedPassword),
        }
        const res = await updatePassword(params)

        if (res.code == 1) {
          ElMessage.success('密码修改成功')
          showPasswordDrawer.value = false

          // 强制用户退出
          ElMessage.warning({
            message: '密码已修改，请重新登录',
            duration: 1000,
            onClose: () => {
              // 用户退出
              userStore.logOut()
              // 清空用户数据
              // userStore.resetState()
              // 跳转到登录页
              window.location.href = '/login'
            },
          })
        } else {
          throw new Error(res.message || '密码修改失败')
        }

        // 重置表单
        passwordForm.originPassword = ''
        passwordForm.newPassword = ''
        passwordForm.checkedPassword = ''
      } catch (error) {
        ElMessage.error('密码修改失败: ' + error.message)
      } finally {
        passwordLoading.value = false
      }
    }
  })
}

// 关闭头像上传对话框
const handleCloseAvatarDialog = () => {
  showAvatarDialog.value = false
  avatarUrl.value = ''
}
</script>

<style lang="less" scoped>
.user-info-container {
  width: 100%;
  //padding: 20px;
}

.user-info-card {
  background-color: #fff;
  border-radius: 8px;
  box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.05);
  padding: 20px;
  margin-bottom: 20px;
}

.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  border-bottom: 1px solid #f0f0f0;
  padding-bottom: 15px;
  margin-bottom: 20px;
}

.title {
  font-size: 18px;
  color: #333;
  font-weight: 500;
  margin: 0;
}

.card-content {
  display: flex;
  justify-content: space-between;
}

.info-section {
  flex: 1;
}

.info-row {
  margin-bottom: 20px;
  display: flex;
}

.info-label {
  width: 100px;
  color: #606266;
  text-align: right;
  margin-right: 20px;
  font-weight: 500;
}

.info-value {
  color: #333;
  flex: 1;
}

.avatar-section {
  width: 200px;
  display: flex;
  justify-content: center;
  align-items: center;
}

.user-avatar {
  border: 2px solid #f0f0f0;
}

.edit-avatar {
  color: #409eff;
  font-size: 14px;
}

.user-info-root {
  width: 100%;
  height: 100%;
}

.preview-container {
  margin-top: 20px;
  text-align: center;
}

.avatar-upload-container {
  display: flex;
  flex-direction: column;
  align-items: center;
}

.avatar-preview {
  width: 200px;
  height: 200px;
  border-radius: 4px;
  overflow: hidden;
  margin-bottom: 20px;
  border: 1px dashed #d9d9d9;
  background-color: #fafafa;
  cursor: pointer;
  transition: all 0.3s;
}

.avatar-preview:hover {
  border-color: #409eff;
  background-color: #f0f7ff;
}

.drag-over {
  border-color: #409eff;
  background-color: #f0f7ff;
  border-style: solid;
  box-shadow: 0 0 8px rgba(64, 158, 255, 0.5);
}

.preview-image {
  width: 100%;
  height: 100%;
  object-fit: cover;
}

.preview-placeholder {
  width: 100%;
  height: 100%;
  display: flex;
  flex-direction: column;
  justify-content: center;
  align-items: center;
  color: #909399;
  font-size: 14px;
}

.preview-placeholder .el-icon {
  font-size: 28px;
  margin-bottom: 8px;
  color: #c0c4cc;
}

.avatar-actions {
  display: flex;
  justify-content: center;
  align-items: center;
  gap: 16px;
}

.avatar-tips {
  margin-top: 20px;
  text-align: center;
  color: #909399;
  font-size: 12px;
}
</style>
